/**
 * @param {number} length - 数组长度
 * @param {number} [min=0] - 最小值（含）
 * @param {number} [max=100] - 最大值（含）
 * @param {boolean} [intMode=true] - 是否生成整数
 * @returns {number[]} 生成的数组
 */
export const generateRandomArray = (length: number, min = 0, max = 100, intMode = true) => {
    ;[min, max] = [Math.min(min, max), Math.max(min, max)]
    const generator = intMode ? () => Math.floor(Math.random() * (max - min + 1)) + min : () => Math.random() * (max - min) + min
    return Array.from({ length: length }, generator)
}

// 生成唯一值数组（无重复）
export const uniqueArray = (length: number, min = 0, max = 100, intMode = true) => {
    const set = new Set()
    while (set.size < length) {
        set.add(generateRandomArray(1, min, max, intMode))
    }
    return [...set].flat()
}
export const generateUniqueArray = (length: number, min: number = 0, max: number = 100, intMode: boolean = true): number[] => {
    // 范围有效性校验
    const [realMin, realMax] = [Math.min(min, max), Math.max(min, max)]
    const rangeSize = intMode ? realMax - realMin + 1 : Infinity

    // 防死循环保护
    if (intMode && rangeSize < length) {
        throw new Error(`无法生成 ${length} 个唯一值（可用范围仅 ${rangeSize} 个数）`)
    }

    // 性能优化：大范围使用Fisher-Yates算法
    if (rangeSize <= 10000) {
        const pool = Array.from({ length: rangeSize }, (_, i) => realMin + i)
        for (let i = pool.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1))
            ;[pool[i], pool[j]] = [pool[j], pool[i]]
        }
        return pool.slice(0, length)
    }

    // 动态生成模式（带碰撞检测）
    const set = new Set<number>()
    while (set.size < length) {
        const value = intMode ? Math.floor(Math.random() * (realMax - realMin + 1)) + realMin : Math.random() * (realMax - realMin) + realMin

        set.add(intMode ? value : Number(value.toFixed(10)))
    }
    return [...set].flat()
}

// 生成等差数列（带随机偏移）
export const linearArray = (length: number, start: number, step: number, variance?: number) => {
    return Array.from({ length: length }, (_, i) => start + i * step + (variance ? Math.random() * variance * 2 - variance : 0))
}
